#include "storage_system_cpp/StorageManager.h"
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>

int main() {
    std::cout << "=== 数据持久化测试程序 ===" << std::endl;

    // 创建存储管理器
    MiniDB::StorageManager storage_manager(20, MiniDB::ReplacementPolicy::LRU);

    // 检查现有的表
    auto existing_tables = storage_manager.getTableNames();
    std::string table_name = "persistence_test";

    std::cout << "📋 现有的表: ";
    for (const auto& table : existing_tables) {
        std::cout << table << " ";
    }
    std::cout << std::endl;

    // 如果表不存在，创建它并插入数据
    if (std::find(existing_tables.begin(), existing_tables.end(), table_name) == existing_tables.end()) {
        std::cout << "\n🏗️ 表 '" << table_name << "' 不存在，正在创建..." << std::endl;
        if (storage_manager.createTable(table_name)) {
            std::cout << "✅ 表 '" << table_name << "' 创建成功" << std::endl;
        } else {
            std::cout << "❌ 表 '" << table_name << "' 创建失败" << std::endl;
            return 1;
        }

        // 插入测试数据
        std::vector<std::string> test_data = {
            "测试数据1",
            "测试数据2",
            "测试数据3"
        };

        for (size_t i = 0; i < test_data.size(); ++i) {
            MiniDB::Record record(static_cast<int>(i + 1), test_data[i]);
            if (storage_manager.insertRecord(table_name, record)) {
                std::cout << "✅ 插入记录成功: ID=" << (i + 1) << ", Data='" << test_data[i] << "'" << std::endl;
            } else {
                std::cout << "❌ 插入记录失败: ID=" << (i + 1) << std::endl;
            }
        }
    } else {
        std::cout << "\n✅ 表 '" << table_name << "' 已存在，正在检查数据..." << std::endl;
    }

    // 查询并显示数据
    auto records = storage_manager.getRecords(table_name);
    std::cout << "\n📋 表 '" << table_name << "' 中的记录 (" << records.size() << " 条):" << std::endl;
    for (const auto& record : records) {
        if (!record.is_deleted) {
            std::cout << "  ID: " << record.id << ", Data: '" << record.data << "'" << std::endl;
        }
    }

    // 强制刷新所有数据
    if (storage_manager.flushAll()) {
        std::cout << "\n✅ 所有数据已刷新到磁盘" << std::endl;
    } else {
        std::cout << "\n❌ 数据刷新失败" << std::endl;
    }

    std::cout << "\n=== 测试完成 ===" << std::endl;
    std::cout << "现在请重新运行这个程序来验证数据是否仍然存在" << std::endl;

    return 0;
}
